package com.edu.chapter07;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter4.BaseQuickAdapter;
import com.edu.chapter07.adapter.WaterfallAdapter;
import com.edu.chapter07.bean.ItemBean;

import java.util.ArrayList;

public class WaterfallActivity extends AppCompatActivity implements BaseQuickAdapter.OnItemChildClickListener<ItemBean> {
    RecyclerView recyclerView;
    WaterfallAdapter waterfallAdapter;
    ArrayList<ItemBean> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_waterfall);

        // 初始化 RecyclerView 与瀑布流管理器
        recyclerView = findViewById(R.id.rv_waterfall);
        recyclerView.setLayoutManager(
                new GridLayoutManager(
                        WaterfallActivity.this,
                        2,
                        GridLayoutManager.VERTICAL,
                        false));

        waterfallAdapter = new WaterfallAdapter();
        initList();
        waterfallAdapter.addAll(list);
        recyclerView.setAdapter(waterfallAdapter);

        waterfallAdapter.setOnItemClickListener((baseQuickAdapter, view, i)
                -> Toast.makeText(WaterfallActivity.this,
                list.get(i).getTitle(),
                Toast.LENGTH_SHORT).show());
        waterfallAdapter.addOnItemChildClickListener(R.id.item_waterfall, this);
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<ItemBean, ?> baseQuickAdapter, @NonNull View view, int i) {
        // 获取当前Item的实时位置（解决索引滞后问题）
//        int realPosition = recyclerView.getChildLayoutPosition(view);
        if (view.getId() == R.id.item_waterfall) {
            Toast.makeText(WaterfallActivity.this,
                    list.get(i).getImageUrl(),
                    Toast.LENGTH_SHORT).show();
            baseQuickAdapter.removeAt(i); // 内部已包含 notifyItemRemoved 和索引更新
        } else if (view.getId() == R.id.iv_image) {
            if (i != RecyclerView.NO_POSITION) {
                baseQuickAdapter.removeAt(i); // 内部已包含 notifyItemRemoved 和索引更新
            }
        }
    }

    private void initList() {
        list = new ArrayList<>();
        list.add(new ItemBean("A", "url:--"));
        list.add(new ItemBean("B", "url:--"));
        list.add(new ItemBean("C", "url:--"));
        list.add(new ItemBean("D", "url:--"));
        list.add(new ItemBean("E", "url:--"));
        list.add(new ItemBean("F", "url:--"));
    }

}